import json

from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from research.models import Research


def research(request):
    research_list = Research.objects.all()
    return render(request, 'research.html', {'research_list': research_list})


def research_manage(request):
    researches = Research.objects.all()
    researches_data = [
        {
            'id': research.id,
            'name': research.name,
            'device_info': research.device_info,
            'achievement': research.achievement,
            'partner': research.partner,
        } for research in researches
    ]
    return JsonResponse({'researches': researches_data})


from .models import Research


@require_http_methods(["POST"])
def update_research(request, research_id):
    try:
        data = json.loads(request.body)
        research = Research.objects.get(pk=research_id)
        research.name = data.get('name', research.name)
        research.device_info = data.get('device_info', research.device_info)
        research.achievement = data.get('achievement', research.achievement)
        research.partner = data.get('partner', research.partner)
        research.save()
        return JsonResponse({'message': 'Research updated successfully'})
    except Research.DoesNotExist:
        return JsonResponse({'error': 'Research not found'}, status=404)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=400)


@require_http_methods(["DELETE"])
def delete_research(request, research_id):
    try:
        research = Research.objects.get(pk=research_id)
        research.delete()
        return JsonResponse({'message': 'Research deleted successfully'})
    except Research.DoesNotExist:
        return JsonResponse({'error': 'Research not found'}, status=404)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=400)


@csrf_exempt
def create_research(request):
    if request.method == "POST":
        data = json.loads(request.body)
        research = Research.objects.create(
            name=data['name'],
            device_info=data['device_info'],
            achievement=data['achievement'],
            partner=data['partner']
        )
        return JsonResponse({'message': 'Research created successfully', 'id': str(research.id)}, status=201)
    else:
        return JsonResponse({'error': 'Invalid HTTP method'}, status=405)
